﻿using System;
using System.Collections.Generic;
using UnityEngine;
using Yoozoo.Framework.Core;
using Yoozoo.Managers.ResourceManagerV2.Runtime;

namespace Gameplay.PVE.Survivor
{
    public class SearchTargetHelper
    {
        public static BattleUnit GetSkillTarget(BattleUnit unit, SkillBase skill,bool ignoreCastRange = false)
        {
            var config = skill.config;
            BattleUnit target = null;
            var castRange = skill.config.cast_range;
            if (ignoreCastRange)
            {
                castRange = 99999;
            }
            if (skill.config.search_sort == (int)EBattleSkillSearchSort.Random)
            {
                var randomType = (EBattleSkillSearchRandom)config.GetParam("RandomType");
                if (randomType == EBattleSkillSearchRandom.TragetRange)
                {
                    var targetrange = config.GetParam("RandomCastRange");
                    var search_sort = (EBattleSkillSearchSort)config.GetParam("RandomTargetSearchSort");
                    target = UnitManager.Instance.SearchTarget(unit, skill.GetTargetTeam(),
                        search_sort, targetrange);
                }
                else
                {
                    target = UnitManager.Instance.SearchTarget(unit, skill.GetTargetTeam(),
                        EBattleSkillSearchSort.Random,  castRange);
                }
            }
            else if (config.search_sort == (int)EBattleSkillSearchSort.Self)
            {
                target = unit;
            }
            else
            {
                target = UnitManager.Instance.SearchTarget(unit, skill.GetTargetTeam(),
                    (EBattleSkillSearchSort)config.search_sort, castRange);
            }

            return target;
        }

        public static Vector3 GetSkillTargetPosition(BattleUnit unit, SkillBase skill,ref BattleUnit targetUnit,bool ignoreCastRange = false)
        {
            if (skill.searchSort == EBattleSkillSearchSort.Random)
            {
                float angle = UnityEngine.Random.Range(0f, Mathf.PI * 2);
                float distance = UnityEngine.Random.Range(0f, skill.config.cast_range);
                float x = unit.Position.x + distance * Mathf.Cos(angle);
                float z = unit.Position.z + distance * Mathf.Sin(angle);
                return new Vector3(x, unit.Position.y, z);
            }
            else
            {
                targetUnit = GetSkillTarget(unit, skill,ignoreCastRange);
                if (targetUnit != null)
                {
                    return targetUnit.position;
                }
                else
                {
                    return unit.Position + unit.Forward * skill.config.cast_range;
                }
            }
        }
    }
}